/*
 * Copyright 2010 Groupware.cc All right reserved. This software is the
 * confidential and proprietary information of Groupware.cc ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Groupware.cc.
 */
package com.rome.syncml.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.vcard.Parameter;
import net.fortuna.ical4j.vcard.Property;
import net.fortuna.ical4j.vcard.VCard;
import net.fortuna.ical4j.vcard.VCardBuilder;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;

import com.rome.syncml.bean.Contact;
import com.rome.syncml.bean.TagType;
import com.rome.syncml.bean.Telphone;
import com.rome.syncml.bean.VcardValue;

/**
 * 类ContractUtil.java的实现描述：TODO 类实现描述 
 * @author 11 2011-11-5 下午04:26:50
 */
public class ContactUtil {

    private static final Logger log = Logger.getLogger(ContactUtil.class);
    private static Pattern chinesePattern = Pattern.compile("[\u4e00-\u9fa5]");
    public static Contact getContact(String content){
        if(StringUtils.isEmpty(content)){
            return null;
        }
        
        try {
            InputStream in = new ByteArrayInputStream(content.getBytes("utf-8"));
            VCardBuilder cb = new VCardBuilder(in);
            VCard card = cb.build();
            Contact contract = new Contact();
            List<Property> ps = card.getProperties();
            for(Property p : ps){
                switch (p.getId()) {
                    case N:
                        if(!StringUtils.isEmpty(p.getValue())){
                            String[] names = p.getValue().split(";");
                            if(names.length > 0){
                                contract.setFamilyName(names[0]);
                            }
                            if(names.length>1){
                                contract.setShortName(names[1]);
                            }
                        }
                        break;
                    case TEL :
                        if(!StringUtils.isEmpty(p.getValue())){
                            VcardValue tel = buildValue(p);
                            List<VcardValue> list = contract.getTelphones();
                            if(list == null){
                                list = new ArrayList<VcardValue>();
                                contract.setTelphones(list);
                            }
                            list.add(tel);
                        }
                        break;
                    case BDAY :
                        String brithday = p.getValue();
                        contract.setBrithday(DateUtil.getDate(brithday));
                        break;
                    case FN :
                        String fullName = p.getValue();
                        contract.setFullName(fullName);
                        if(!StringUtils.isEmpty(fullName)){
                            HanyuPinyinOutputFormat hanYuPinOutputFormat = new HanyuPinyinOutputFormat();
                            char[] temp = fullName.toCharArray();
                            Matcher m = chinesePattern.matcher(fullName.substring(0,1));
                            if(m.matches()){
                                String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(temp[0],hanYuPinOutputFormat);
                                if(pinyin.length>0 && pinyin[0].length()>0)contract.setInitial(pinyin[0].substring(0,1).toUpperCase());
                            }else{
                                contract.setInitial(fullName.substring(0,1).toUpperCase());
                            }
                            
                        }
                        break;
                    case EMAIL :
                        if(!StringUtils.isEmpty(p.getValue())){
                            VcardValue email = buildValue(p);
                            List<VcardValue> list = contract.getEmails();
                            if(list == null){
                                list = new ArrayList<VcardValue>();
                                contract.setEmails(list);
                            }
                            list.add(email);
                        }
                        break;
                    case URL :
                        if(!StringUtils.isEmpty(p.getValue())){
                            VcardValue url = buildValue(p);
                            List<VcardValue> list = contract.getUrls();
                            if(list == null){
                                list = new ArrayList<VcardValue>();
                                contract.setUrls(list);
                            }
                            list.add(url);
                        }
                        break;
                    case ADR :
                        if(!StringUtils.isEmpty(p.getValue())){
                            contract.setAddress(p.getValue());
                        }
                        break;
                    default:
                        break;
                }
                
            }
            return contract;
        } catch (Exception e) {
            log.error("build vcard error",e);
            return null;
        }
    }

    /**
     * @param p
     * @return
     */
    private static VcardValue buildValue(Property p) {
        VcardValue value = new VcardValue();
        value.setValue(p.getValue());
        List<Parameter> params = p.getParameters();
        for(Parameter param : params){
            if(param.getId() == Parameter.Id.TYPE){
                value.setTag(param.getValue());
                break;
            }
        }
        return value;
    }
    
    public static String getVcard(Contact contact){
        StringBuilder sb = new StringBuilder();
        sb.append("BEGIN:VCARD\n");
        sb.append("VERSION:3.0\n");
        sb.append("FN:" + contact.getFullName() + "\n");
        sb.append("N:" + contact.getFamilyName() + ";" + contact.getShortName() + "\n");
        sb.append("PROFILE:VCARD\n");
        sb.append("NICKNAME:\n");
        if(contact.getTelphones()!=null){
            for(VcardValue value : contact.getTelphones()){
                sb.append("TEL;TYPE=" + value.getTag() + ":" + value.getValue() + "\n");
            }
        }
        if(contact.getEmails()!=null){
            for(VcardValue value : contact.getEmails()){
                sb.append("EMAIL;TYPE=" + value.getTag() + ":" + value.getValue()+ "\n");
            }
        }
        if(contact.getUrls() != null){
            for(VcardValue value : contact.getUrls()){
                sb.append("URL;TYPE=" + value.getTag() + ":" + value.getValue() + "\n");
            }
        }
        if(StringUtils.isNotEmpty(contact.getAddress())){
            sb.append("ADR;HOME:" + contact.getAddress() + "\n");
        }
        if(contact.getBrithday() != null){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            sb.append("BDAY:" + format.format(contact.getBrithday()) + "\n");
        }
        sb.append("END:VCARD\n");
        return sb.toString();
    }
    
}
